const Router = require('koa-router')
const filesController = require('../controller/files')
const multer = require('koa-multer')
const fse = require('fs-extra')
const path = require('path')
const tools = require('../utils/tools')
const router = new Router()

//文件上传配置
const storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/')
    },
    //修改文件名称
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})
//加载配置
const upload = multer({ storage: storage })

// 静态资源服务器
// 一级资源文件夹
router.post('/public', filesController.getAllFiles)
// 二级资源文件夹
router.post('/public/:directory', filesController.getFiles)

// 上传文件接口（v1.0/v2.0/v3.0）
router.post('/files/upload', upload.single('file'), async(ctx, next) => {
    return ctx.body = {
        code: '0',
        filename: ctx.req.file.filename,
        desc: '资源上传成功~'
    } 
})

// 上传文件接口（v4.0）
router.post('/files/chunk', async ctx => {
    let {
        files,
        body: { hash, name }
    } = ctx.request
    const file = files.file
    const filePath = path.resolve(__dirname, `../public/uploads/${hash}`)
    if (!fse.existsSync(filePath)) {
      try { 
        await fse.mkdir(filePath)
      } catch(err) {
        return ctx.body = {
            code: '-1',
            desc: err
        } 
      }
    }
    try {
        await fse.move(file.path, `${filePath}/${name}`)
    } catch(err) {
        return ctx.body = {
            code: '-1',
            desc: err
        } 
    }
    ctx.body = `切片${name}上传成功`
})
router.post('/files/merge', async ctx => {
    let { ext, size, hash } = ctx.request.body
    // 最终生成的文件路径+名称
    const filePath = path.resolve(__dirname, `../public/uploads/${hash}.${ext}`)
    try {
        await tools.mergeFile(filePath, hash, size)
        return ctx.body = {
            code: '0',
            filename: `${hash}.${ext}`,
            desc: '资源上传成功~'
        }
    } catch(err) {
        return ctx.body = {
            code: '-1',
            desc: err
        } 
    }
    
})


module.exports = router